package com.c2001.springboot.service.impl;

import cn.hutool.core.date.DateUnit;
import com.c2001.springboot.controller.request.BaseRequest;
import com.c2001.springboot.dao.BorrowDao;
import com.c2001.springboot.dao.DistributionDao;
import com.c2001.springboot.dao.LibPointDao;
import com.c2001.springboot.dao.UserDao;
import com.c2001.springboot.domain.Borrow;
import com.c2001.springboot.domain.Distribution;
import com.c2001.springboot.domain.LibPoint;
import com.c2001.springboot.domain.User;
import com.c2001.springboot.enums.BusEnums;
import com.c2001.springboot.enums.OperateTypeEnum;
import com.c2001.springboot.service.IBookService;
import com.c2001.springboot.service.IBorrowService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class BorrowService implements IBorrowService {
    @Autowired
    BorrowDao borrowDao;

    @Autowired
    private UserDao userDao;

    @Autowired
    private DistributionDao distributionDao;

    @Autowired
    private LibPointDao  libPointDao;

    @Override
    public List<Borrow> getList() {
        return borrowDao.list();
    }

    public PageInfo<Borrow> getPage(BaseRequest baseRequest,Integer buyed) {
        baseRequest.setBuyed(buyed);
        Integer level = baseRequest.getLevel();
        if (Objects.equals(0,level)){
            baseRequest.setStuname(baseRequest.getStuname());
            baseRequest.setStunumber(baseRequest.getStunumber());
        }
        PageHelper.startPage(baseRequest.getPageNum(), baseRequest.getPageSize());
        // 管理员可以看全部 否则只能看自己的
        List<Borrow> borrows = borrowDao.listByCondition(baseRequest);
        Map<Integer, String> busStatusMap = Arrays.stream(BusEnums.values()).collect(Collectors.toMap(BusEnums::getCode, BusEnums::getDesc));
        borrows.forEach(e -> {
            e.setBuyedStr("否");
            e.setBusStatusStr(busStatusMap.getOrDefault(e.getBusStatus(),"未发货"));
            Date createtime = e.getCreatetime() == null? new Date():e.getCreatetime();
            LocalDate localDate = createtime.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
            LocalDate years = localDate.plusYears(1);
            long timestamp = years.atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli();
            e.setBacktime(new Date(timestamp));
            if (Objects.equals(1, e.getBuyed())) {
                e.setBuyedStr("是");
            }
        });
        return new PageInfo<>(borrows);
    }

    public void add(Borrow book) {
        //自动生成username,唯一 扣款
        book.setBuyed(0);
        Integer rentPrice = book.getRentPrice() == null ? 0 : book.getRentPrice();
        String stuname = book.getStuname();
        String stunumber = book.getStunumber();
        User bookByUser = userDao.borrowBookByUser(stuname, stunumber);
        Integer money = bookByUser.getMoney();
        Integer id = bookByUser.getId();
        money -= rentPrice;

        userDao.descUserMoney(money, id);

        Distribution distribution = new Distribution();
        distribution.setLogicCode(UUID.randomUUID().toString());
        distribution.setStatus(0);
        distribution.setBusStatus(0);
        distribution.setAddress("待联系");
        distribution.setCreateTime(new Date());
        distribution.setUpdateTime(new Date());
        distribution.setBookId(book.getBookId());
        distribution.setStuname(book.getStuname());

        distributionDao.insert(distribution);
        borrowDao.add(book);

        LibPoint libPoint = new LibPoint();
        libPoint.setLogicCode(UUID.randomUUID().toString());
        libPoint.setType(OperateTypeEnum.buy.getCode());
        libPoint.setDesc(OperateTypeEnum.buy.getDesc());
        libPoint.setUser(book.getStuname());
        libPoint.setCreateTime(new Date());
        libPoint.setUpdateTime(new Date());
        libPointDao.insert(libPoint);
    }

    @Override
    public Borrow getById(Integer id) {
        return borrowDao.getById(id);
    }

    @Override
    public void update(Borrow book) {

        borrowDao.update(book);
    }

    @Override
    public void delete(Integer id) {
        borrowDao.deleteById(id);
        return;
    }

    @Override
    public void handleFinSend(Long diId) {
        // 需要数据主键
        Distribution distribution = new Distribution();
        distribution.setId(diId);
        distribution.setBusStatus(BusEnums.fin_send.getCode());
        distributionDao.updateByPrimaryKeySelective(distribution);
    }

    @Override
    public void handleSend(Long diId) {
        // 需要数据主键
        Distribution distribution = new Distribution();
        distribution.setId(diId);
        distribution.setBusStatus(BusEnums.send.getCode());
        distributionDao.updateByPrimaryKeySelective(distribution);
    }


}
